package com.tanhua.dubbo.api;

import com.tanhua.manage.domain.mongo.Comment;
import com.tanhua.manage.domain.mongo.Publish;
import com.tanhua.manage.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@Service
public class CommentApiImpl implements CommentApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 点赞功能
     */
    @Override
    public long save(Comment comment) {
        //1. 通过动态id来获取作者id
        // 1.1 构建动态表的查询条件
        ObjectId publishId = comment.getTargetId();
        Query publishQuery = new Query(Criteria.where("_id").is(publishId));
        // 1.2 查询动态表,获取作者id
        Publish publish = mongoTemplate.findOne(publishQuery, Publish.class);
        Long authorId = publish.getUserId();
        comment.setTargetUserId(authorId);
        //2. 补充创建时间
        comment.setCreated(System.currentTimeMillis());
        //3.添加点赞数据
        mongoTemplate.insert(comment);
        //4.更新动态的点赞数据
        //  4.1 构建动态的条件, 上面已经构建过了，可重用
        //  4.2 使用Update.inc
        Update update = new Update();
        update.inc(comment.getCol(),1);// 点赞数自增1
        mongoTemplate.updateFirst(publishQuery,update,Publish.class);

        //5.查询最新的点赞数
        Publish after = mongoTemplate.findOne(publishQuery,Publish.class);

        if (comment.getCommentType() == 3){
            return after.getLoveCount();
        }
        return after.getLikeCount();
    }

    /**
     * 取消点赞功能
     */
    @Override
    public long remove(Comment comment) {

        ObjectId publishId = comment.getTargetId();
        Long authorId = comment.getTargetUserId();
        Integer commentType = comment.getCommentType();

        Query query = new Query();
        query.addCriteria(Criteria.where("targetId").is(publishId).and("userId").is(authorId).and("commentType").is(commentType));

        mongoTemplate.remove(query,Comment.class);

        Query updateQuery = new Query();
        updateQuery.addCriteria(Criteria.where("_id").is(publishId));
        Update update = new Update();
        update.inc(comment.getCol(),-1);

        mongoTemplate.updateFirst(updateQuery, update, Publish.class);

        Publish after = mongoTemplate.findOne(updateQuery, Publish.class);

        if (comment.getCommentType() == 3){
            return after.getLoveCount();
        }
        return after.getLikeCount();
    }

    /**
     * 通过动态id查询评论列表
     */
    @Override
    public PageResult findPage(String publishId, Long page, Long pageSize) {

        Query query = new Query(Criteria.where("targetId").is(new ObjectId(publishId)).and("commentType").is(2));
        Long total = mongoTemplate.count(query,Comment.class);
        List<Comment> comments = new ArrayList<>();
        if (total>0) {
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            comments = mongoTemplate.find(query, Comment.class);
        }
        return PageResult.pageResult(page,pageSize,comments,total);
    }

    @Override
    public long likeComment(Comment comment) {
        Comment commentInDB = mongoTemplate.findById(comment.getTargetId(), Comment.class);
        comment.setTargetUserId(commentInDB.getUserId());
        comment.setCreated(System.currentTimeMillis());

        mongoTemplate.insert(comment);

        Query query = new Query(Criteria.where("_id").is(commentInDB.getId()));
        Update update = new Update();
        update.inc("likeCount",1);
        mongoTemplate.updateFirst(query,update,Comment.class);

        Comment after = mongoTemplate.findById(commentInDB.getId(), Comment.class);
        return after.getLikeCount();
    }

    @Override
    public long dislikeComment(Comment comment) {


        Query query = new Query(Criteria.where("targetId").is(comment.getTargetId()).and("userId").is(comment.getUserId()).and("commentType").is(1));
        mongoTemplate.remove(query);

        query = new Query(Criteria.where("_id").is(comment.getTargetId()));
        Update update = new Update();
        update.inc("likeCount",-1);
        mongoTemplate.updateFirst(query,update,Comment.class);
        Comment after = mongoTemplate.findById(comment.getTargetId(),Comment.class);
        return after.getLikeCount();
    }
    /**
     * 按登陆用户id 通过commentType分页查询 评论信息
     * @param userId
     * @param commentType
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPageByUserId(Long userId, int commentType, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("targetUserId").is(userId).and("commentType").is(commentType));
        Long count = mongoTemplate.count(query,Comment.class);
        List<Comment> comments = new ArrayList<>();
        if (count>0){
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));

            comments = mongoTemplate.find(query, Comment.class);
        }

        return PageResult.pageResult(page,pageSize,comments,count);
    }
}
